package com.zdlyh.controller;

import com.zdlyh.domain.ResponseResult;
import com.zdlyh.domain.dto.UserDto;
import com.zdlyh.domain.entity.User;
import com.zdlyh.enums.AppHttpCodeEnum;
import com.zdlyh.exception.SystemException;
import com.zdlyh.service.BlogLoginService;
import com.zdlyh.service.MailboxService;
import com.zdlyh.utils.ValidateCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "前端登录",description = "登录相关接口")
public class BlogLoginController {
    @Autowired
    private BlogLoginService blogLoginService;

    @PostMapping("/login")
    @ApiOperation(value = "登录",notes = "根据邮箱号和密码登录")
    // 前端传回来的json对象必须要加RequestBody进行转换，不然接收不到前端传回来的数据
    public ResponseResult login(@RequestBody UserDto user){
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return blogLoginService.login(user);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "退出登录",notes = "清除Redis中的用户信息")
    public ResponseResult logout(){
        return blogLoginService.logout();
    }

    // 邮件发送人
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Resource
    private MailboxService mailboxService;

    @PostMapping("/send")
    @ApiOperation(value = "邮箱验证码",notes = "发送邮箱验证码")
    public ResponseResult sendMsg(@RequestBody User user) {
        String email = user.getEmail();
        if (email != null) {
            System.out.println("验证码开始发送---------");
            String code = ValidateCodeUtil.generateValidateCode(4).toString();
            String context = "塑梦博客：您的登录验证码为 " + code + "，五分钟内有效，请妥善保管!";
            String subject = "塑梦博客";
            // 真正地发送邮箱验证码
            mailboxService.sendMsg(email, subject, context,from);

            // 验证码缓存到Redis中，并且设置验证码的有效时间为 5分钟
            redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
            System.out.println("验证码发送成功，请及时查看!");
        }
        return ResponseResult.okResult();
    }
}
